package com.services
{
	import com.model.Book_VO;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ArrayUtil;
	
	public class GetBooksService extends BasicService
	{
		public var books: ArrayCollection;
		
		public function GetBooksService(userId:Number, busyCursor:Boolean=false, callBack:Function=null)
		{
			var url:String = IslamicBook.BACKEND_URL + "books.xml";
			super(url, "POST", busyCursor, callBack);
			
			var paramters:Object = new Object();
			paramters["user_id"] = userId;
			service.requestTimeout = 30;
			send();//paramters);
		}
		
		override public function resultHandler(event:ResultEvent):void
		{
			if(event.result.books && event.result.books.book != null) {
				if(event.result.books.book != null)	{
					var books: ArrayCollection = 
						event.result.books.book is ArrayCollection ?
						event.result.books.book : new ArrayCollection(ArrayUtil.toArray(event.result.books.book));
					constructBooks(books);
				}
			}else if (event.result.book) {
				var obj:Object = event.result.book; 
				this.books = new ArrayCollection();
				this.books.addItem(new Book_VO(obj.id.valueOf(), obj['title'].valueOf(),obj['number-of-pages'].valueOf()));					
			}
			
			super.resultHandler(event);
		}
		
		private function constructBooks(items:ArrayCollection):void
		{
			this.books = new ArrayCollection();
			for(var i:int = 0; i < items.length; i++)
			{
				this.books.addItem(new Book_VO(items[i].id.valueOf(), items[i]['title'].valueOf(), items[i]['number-of-pages'].valueOf()));
			} 
		}	
		
		override public function faultHandler(event:FaultEvent):void
		{
			Alert.show(event.toString());
		}
	}
}